package service

import (
	"context"
	"fmt"
	"log"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/dao"
	"order_srv/handler/models"
	"strings"
	"time"
)

// 导出订单（优化版）
func (s *Server) ExportOrder(ctx context.Context, in *__.ExportOrderReq) (*__.ExportOrderResp, error) {
	// 记录开始时间
	startTime := time.Now()

	// 创建导出任务
	task, err := dao.CreateExportTask(in)
	if err != nil {
		log.Printf("创建导出任务失败: %v", err)
		return &__.ExportOrderResp{
			TaskId:  "",
			Status:  "failed",
			Message: fmt.Sprintf("创建任务失败: %v", err),
		}, nil
	}

	log.Printf("创建导出任务成功: TaskId=%s, UserId=%d, 耗时=%v",
		task.TaskId, task.UserId, time.Since(startTime))

	// 返回任务信息
	return &__.ExportOrderResp{
		TaskId:  task.TaskId,
		Status:  "created",
		Message: "任务创建成功，正在处理中",
	}, nil
}

// 获取导出任务状态（优化版）
func (s *Server) GetExportTaskStatus(ctx context.Context, in *__.GetExportTaskStatusReq) (*__.GetExportTaskStatusResp, error) {
	// 根据任务ID查询任务状态
	task, err := dao.GetExportTaskStatusV2(in.TaskId)
	if err != nil {
		log.Printf("查询任务状态失败: TaskId=%s, Error=%v", in.TaskId, err)
		return nil, fmt.Errorf("查询任务失败: %v", err)
	}

	// 检查用户权限
	if task.UserId != in.UserId {
		return nil, fmt.Errorf("无权限访问该任务")
	}

	// 构建并返回响应
	return &__.GetExportTaskStatusResp{
		TaskId:       task.TaskId,
		Status:       uint32(task.Status),
		TotalCount:   task.TotalCount,
		Processed:    task.Processed,
		FilePath:     task.FilePath,
		ErrorMsg:     task.ErrorMsg,
		CreatedAt:    task.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdatedAt:    task.UpdatedAt.Format("2006-01-02 15:04:05"),
		CompletedAt:  formatTime(task.CompletedAt),
		FileSize:     task.FileSize,
		IsEncrypted:  task.IsEncrypted,
		DownloadUrl:  task.DownloadUrl,
		Progress:     task.Progress,
		TaskType:     getTaskTypeNameOrder(task.TaskType),
		ExportFormat: task.ExportFormat,
	}, nil
}

// 获取导出任务列表
func (s *Server) GetExportTaskListOrder(ctx context.Context, in *__.GetExportTaskListOrderReq) (*__.GetExportTaskListOrderResp, error) {
	// 参数校验
	if in.Page <= 0 {
		in.Page = 1
	}
	if in.PageSize <= 0 {
		in.PageSize = 10
	}
	if in.PageSize > 100 {
		in.PageSize = 100 // 限制最大页面大小
	}

	// 查询任务列表
	tasks, total, err := dao.GetExportTaskListOrder(in.UserId, int(in.Page), int(in.PageSize), in.Status, in.StartDate, in.EndDate)
	if err != nil {
		log.Printf("查询任务列表失败: UserId=%d, Error=%v", in.UserId, err)
		return nil, fmt.Errorf("查询任务列表失败: %v", err)
	}

	// 转换为响应格式
	var taskInfos []*__.ExportTaskInfoOrder
	for _, task := range tasks {
		taskInfo := &__.ExportTaskInfoOrder{
			TaskId:       task.TaskId,
			UserId:       task.UserId,
			Status:       uint32(task.Status),
			TaskType:     getTaskTypeNameOrder(task.TaskType),
			FileName:     getFileName(task.FilePath),
			FilePath:     task.FilePath,
			FileSize:     task.FileSize,
			TotalCount:   task.TotalCount,
			Processed:    task.Processed,
			CreatedAt:    task.CreatedAt.Format("2006-01-02 15:04:05"),
			CompletedAt:  formatTime(task.CompletedAt),
			ErrorMsg:     task.ErrorMsg,
			IsEncrypted:  task.IsEncrypted,
			DownloadUrl:  task.DownloadUrl,
			Progress:     task.Progress,
			ExportFormat: task.ExportFormat,
		}
		taskInfos = append(taskInfos, taskInfo)
	}

	return &__.GetExportTaskListOrderResp{
		Tasks:    taskInfos,
		Total:    total,
		Page:     in.Page,
		PageSize: in.PageSize,
	}, nil
}

// 删除导出任务
func (s *Server) DeleteExportTaskOrder(ctx context.Context, in *__.DeleteExportTaskOrderReq) (*__.DeleteExportTaskOrderResp, error) {
	err := dao.DeleteExportTaskOrder(in.TaskId, in.UserId)
	if err != nil {
		log.Printf("删除任务失败: TaskId=%s, UserId=%d, Error=%v", in.TaskId, in.UserId, err)
		return &__.DeleteExportTaskOrderResp{
			Success: false,
			Message: fmt.Sprintf("删除任务失败: %v", err),
		}, nil
	}

	return &__.DeleteExportTaskOrderResp{
		Success: true,
		Message: "任务删除成功",
	}, nil
}

// 下载导出文件
func (s *Server) DownloadExportFileOrder(ctx context.Context, in *__.DownloadExportFileOrderReq) (*__.DownloadExportFileOrderResp, error) {
	task, err := dao.DownloadExportFileOrder(in.TaskId, in.UserId)
	if err != nil {
		log.Printf("下载文件失败: TaskId=%s, UserId=%d, Error=%v", in.TaskId, in.UserId, err)
		return &__.DownloadExportFileOrderResp{
			Success: false,
			Message: fmt.Sprintf("下载文件失败: %v", err),
		}, nil
	}

	return &__.DownloadExportFileOrderResp{
		Success:     true,
		Message:     "下载链接生成成功",
		DownloadUrl: task.DownloadUrl,
		FileSize:    task.FileSize,
		FileName:    getFileName(task.FilePath),
		IsEncrypted: task.IsEncrypted,
	}, nil
}

// 获取导出进度
func (s *Server) GetExportProgressOrder(ctx context.Context, in *__.GetExportProgressOrderReq) (*__.GetExportProgressOrderResp, error) {
	task, err := dao.GetExportProgressOrder(in.TaskId, in.UserId)
	if err != nil {
		log.Printf("获取导出进度失败: TaskId=%s, UserId=%d, Error=%v", in.TaskId, in.UserId, err)
		return nil, fmt.Errorf("获取导出进度失败: %v", err)
	}

	// 计算预计剩余时间
	estimatedTime := calculateEstimatedTime(task)

	// 获取当前步骤
	currentStep := getCurrentStep(task)

	return &__.GetExportProgressOrderResp{
		TaskId:          task.TaskId,
		Status:          uint32(task.Status),
		TotalCount:      task.TotalCount,
		Processed:       task.Processed,
		ProgressPercent: task.Progress,
		FilePath:        task.FilePath,
		ErrorMsg:        task.ErrorMsg,
		StartTime:       task.StartTime.Format("2006-01-02 15:04:05"),
		EndTime:         task.EndTime.Format("2006-01-02 15:04:05"),
		FileSize:        task.FileSize,
		DownloadUrl:     task.DownloadUrl,
		EstimatedTime:   estimatedTime,
		CurrentStep:     currentStep,
	}, nil
}

// 辅助函数

// 格式化时间
func formatTime(t *time.Time) string {
	if t == nil {
		return ""
	}
	return t.Format("2006-01-02 15:04:05")
}

// 获取任务类型名称
func getTaskTypeNameOrder(taskType uint8) string {
	switch taskType {
	case 1:
		return "订单导出"
	case 2:
		return "财务对账导出"
	case 3:
		return "用户数据导出"
	default:
		return "未知类型"
	}
}

// 获取文件名
func getFileName(filePath string) string {
	if filePath == "" {
		return ""
	}
	// 从文件路径中提取文件名
	parts := strings.Split(filePath, "/")
	if len(parts) > 0 {
		return parts[len(parts)-1]
	}
	return filePath
}

// 计算预计剩余时间
func calculateEstimatedTime(task *models.ExportTask) string {
	if task.Status != 1 || task.TotalCount == 0 || task.Processed == 0 {
		return "无法预估"
	}

	// 计算处理速度（条/秒）
	elapsed := time.Since(task.CreatedAt).Seconds()
	if elapsed <= 0 {
		return "无法预估"
	}

	speed := float64(task.Processed) / elapsed
	if speed <= 0 {
		return "无法预估"
	}

	// 计算剩余时间
	remaining := task.TotalCount - task.Processed
	estimatedSeconds := float64(remaining) / speed

	// 格式化时间
	if estimatedSeconds < 60 {
		return fmt.Sprintf("%.0f秒", estimatedSeconds)
	} else if estimatedSeconds < 3600 {
		return fmt.Sprintf("%.1f分钟", estimatedSeconds/60)
	} else {
		return fmt.Sprintf("%.1f小时", estimatedSeconds/3600)
	}
}

// 获取当前步骤
func getCurrentStep(task *models.ExportTask) string {
	if task.CurrentStep != "" {
		return task.CurrentStep
	}

	switch task.Status {
	case 0:
		return "等待开始"
	case 1:
		return "正在处理"
	case 2:
		return "已完成"
	case 3:
		return "处理失败"
	default:
		return "未知状态"
	}
}
